using Eno.Application.Dto;
using Eno.Application.Services;
using Eno.Infrastructure.Tools;
using Microsoft.AspNetCore.Mvc;

namespace Eno.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly AuthServices _authService;
    private readonly ILogService _logService;

    public AuthController(AuthServices authServices, ILogService logService)
    {
        _authService = authServices;
        _logService = logService;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register(UserDto userDto)
    {
        try
        {
            // 打印收到的注册参数
            Console.WriteLine($"[Register] 收到注册请求: Account={userDto.Account}, Password={userDto.Password}, DefaultRole={userDto.DefaultRole}, DepartmentId={userDto.DepartmentId}, IsActived={userDto.IsActived}, IsDeleted={userDto.IsDeleted}, Remarks={userDto.Remarks}, Avatar={userDto.Avatar}, DisplayName={userDto.DisplayName}, Email={userDto.Email}, Phone={userDto.Phone}");
            var result = await _authService.RegisterAsync(userDto);
            if (result == 0)
            {
                await _logService.LogWarningAsync("注册用户失败", "AuthController", new { userDto.Account });
                Console.WriteLine($"[Register] 注册失败: Account={userDto.Account}");
                return Ok(Tips<int>.Fail(result, 3474, "注册用户失败"));
            }

            await _logService.LogInfoAsync("注册用户成功", "AuthController", new { userDto.Account });
            Console.WriteLine($"[Register] 注册成功: Account={userDto.Account}");
            return Ok(Tips<int>.Success(result, "注册用户成功"));
        }
        catch (Exception ex)
        {
            await _logService.LogErrorAsync("注册用户异常", ex, "AuthController", new { userDto.Account });
            Console.WriteLine($"[Register] 注册异常: {ex}");
            return Ok(Tips<int>.Fail(0, 3474, "注册失败"));
        }
    }

    [HttpPost("login")]
    public async Task<IActionResult> Access(UserDto userDto)
    {
        try
        {
            // 先校验账号密码
            var isValid = await _authService.EnterAsync(userDto);
            if (!isValid)
            {
                await _logService.LogWarningAsync("身份验证失败", "AuthController", new { userDto.Account });
                return Ok(Tips<string>.Fail("", 3474, "身份验证失败"));
            }

            // 生成 Token，仅用 Account 字段
            var token = await _authService.GenerateTokenAsync(userDto.Account);
            await _logService.LogInfoAsync("用户登录成功", "AuthController", new { userDto.Account });
            return Ok(Tips<string>.Success(token, "身份验证成功"));
        }
        catch (Exception ex)
        {
            await _logService.LogErrorAsync("用户登录异常", ex, "AuthController", new { userDto.Account });
            return Ok(Tips<string>.Fail("", 3474, "登录失败"));
        }
    }
}